import 'dart:convert';
import 'dart:math' as math;

import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:video_player/video_player.dart';
import 'package:yp/Xwidgets/ad_box.dart';
import 'package:yp/config/config.dart';
import 'package:yp/config/style.dart';
import 'package:yp/helper.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/videoplayer/video_player_plus.dart';
import 'package:yp/widgets/button_widget.dart';
import 'package:yp/widgets/index.dart';

import '../../router.dart';

class Discover extends StatefulWidget {
  const Discover({Key key}) : super(key: key);

  @override
  _DiscoverState createState() => _DiscoverState();
}

class _DiscoverState extends State<Discover> with TickerProviderStateMixin {
  List category_info_list = [];
  List Adlist = [
    {'logo': ''}
  ];
  List adrList = [];

  getinfo() {
    var params1 = {
      'page_num': 1,
      'page_size': 100,
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };
    Api.contentcategoryquery(params1).listen((event) {
      if (event['code'] == 0) {
        if (event['category_info_list'] != null &&
            event['category_info_list'].length > 0) {
          category_info_list = event['category_info_list'];
          category_info_list.forEach((element) {
            setState(() {
              tabList2.add(Tab(text: element['category_name']));
              _primaryTC2 =
                  TabController(length: tabList2?.length ?? 0, vsync: this);
            });
            //
          });
        }
        // toast("修改成功");.
      }
    });
  }

  getAdInfo() {
    print('获取广告列表1111');
    var params2 = {
      'page_num': 1,
      'page_size': 100,
      'category_id': null,
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };

    Api.contentquery(params2).listen((event) {
      if (event['code'] == 0) {
        if (event['content_info_list'] != null &&
            event['content_info_list'].length > 0) {
          setState(() {
            event['content_info_list'].forEach((element) {
              adrList = [];
              if (element['is_carousel'] == 1) {
                adrList.add(element);
              }
            });
          });
        }
        print('adrList');
        print(adrList);
        // toast("修改成功");
      }
    });
  }

  // var _tabList = [Tab(text: '购物'), Tab(text: '内容')];
  var _tabList = [Tab(text: '内容')];
  var _tabList1 = [
    Tab(text: '购物'),
    Tab(text: '内容'),
    Tab(text: '随便'),
    Tab(text: '都行')
  ];

  // var tabList2 = [Tab(text: '全部'), Tab(text: '活动')];
  List<Tab> tabList2 = [Tab(text: '全部')];
  var _screenList = [
    {'title': '收藏数', 'isSelected': true, 'order': true},
    {'title': '浏览数', 'isSelected': false, 'order': true},
    {'title': '点赞数', 'isSelected': false, 'order': true}
  ];
  int _screenIndex = 0;
  TabController _primaryTC;
  TabController _primaryTC1;
  TabController _primaryTC2;
  List advertising = [];
  // List advertising = [];
  ScrollController _scrollController = ScrollController();
  int _progress = 0;

  @override
  void initState() {
    super.initState();
    getinfo();
    var params = {
      'adv_category': '5',
      'page_num': 1,
      'page_size': 10,
      'status_num_id': 3
    };
    Api.getAdvertising(params).listen((event) {
      if (event["code"] == 0 && event['list'] != null) {
        setState(() {
          advertising = event['list'];
        });
      } else {
        setState(() {
          advertising = [];
        });
      }
    });
    getAdInfo();

    _primaryTC = TabController(length: _tabList?.length ?? 0, vsync: this);
    _primaryTC1 = TabController(length: _tabList1?.length ?? 0, vsync: this);
    _primaryTC2 = TabController(length: tabList2?.length ?? 0, vsync: this);
  }

  @override
  void dispose() {
    _primaryTC.dispose();
    _primaryTC1.dispose();
    _primaryTC2.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
        BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width,
            maxHeight: MediaQuery.of(context).size.height),
        designSize: Size(750, 1334),
        orientation: Orientation.portrait);
    return Scaffold(
        appBar: YPNavigationBar('发现', onPressed: () {
          // Get.offAllNamed(RouteConfig.main);
          Get.back();
        },
            showLine: false,
            backgroundColor: EsColors.Primary,
            backBtnColor: EsColors.White,
            titleColor: EsColors.White),
        backgroundColor: EsColors.Primary,
        body: CustomScrollView(controller: _scrollController, slivers: [
          SliverToBoxAdapter(
              child: Container(
            height: MediaQuery.of(context).size.height + 420.w,
            color: EsColors.White,
            child: Column(
              children: <Widget>[
                // _tabs(_primaryTC, _tabList),
                adrList.length > 0 ? _banner() : Container(),
                Expanded(
                  child: category_info_list != null
                      ? Column(children: <Widget>[
                          _tabs(_primaryTC2, tabList2, title: false),
                          Expanded(
                              child: ExtendedTabBarView(
                                  children: List<Widget>.generate(
                                      _primaryTC2?.length ?? 0,
                                      (int index) => infoList(
                                          _scrollController,
                                          index == 0
                                              ? null
                                              : category_info_list[index - 1]
                                                  ['category_id'])),
                                  controller: _primaryTC2,

                                  ///打开联动
                                  link: true

                                  /// 缓存页面数 默认是0 传1就会有两个缓存页面 null是缓存全部
                                  // cacheExtent: 0,
                                  ))
                        ])
                      : Container(),

                ),
                SizedBox(height: 20.w)
              ],
            ),
          ))
        ]));
  }

  // 轮播图
  Widget _banner() {
    String imagesString;
    String videoString;
    //   String imagesString = state.goodsDetail['list_images'];
    // String videoString = state.goodsDetail['list_video'];
    // print('------商品宣传图片--------');
    // print(videoString);
    List<String> images = [];
    List<String> videos = [];
    List swiperItems = [];
    List<String> videoFormats = [
      'avi',
      'AVI',
      'wmv',
      'WMV',
      'mp4',
      'MP4',
      'mkv',
      'MKV',
      'flv',
      'FLV'
    ];
    if (imagesString != null && imagesString.isNotEmpty) {
      images = imagesString.split(',');
    }
    if (videoString != null && videoString.isNotEmpty) {
      videos = videoString.split(',');
    }
    // swiperItems = videos.length > 0 ? videos + images : images;
    swiperItems = adrList;
    // print(swiperItems[0].substring(swiperItems[0].length - 3));
    // if ((images == null || images.isEmpty) && (videos == null || videos.isEmpty)) {
    //   return Container(
    //     width: MediaQuery
    //         .of(context)
    //         .size
    //         .width,
    //     height: 300.w,
    //     child: Image.asset(
    //       'assets/images/defaultAvatar_image.png',
    //       width: MediaQuery
    //           .of(context)
    //           .size
    //           .width,
    //       height:300.w,
    //       fit: BoxFit.fill,
    //     ),
    //   );
    // }
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 300.w,
      child: Swiper(
        autoplay: false,
        itemCount: swiperItems.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              Get.toNamed(RouteConfig.eventDetail, arguments: {
                'is_like': swiperItems[index]['is_like'], //是否点赞
                'likes_num': swiperItems[index]['likes_num'], //
                'view_num': swiperItems[index]['view_num'],
                'is_collection': swiperItems[index]['is_collection'], //点赞数量
                'series': swiperItems[index]['series']
              });
            },
            child: Container(
                // child: Image.network(
                //   images[index],
                //   width: MediaQuery.of(context).size.width,
                //   height: MediaQuery.of(context).size.width,
                //   fit: BoxFit.fill,
                // ),
                // swiperItems[index].indexOf('.mp4') != -1
                child: swiperItems[index]['video_url'].length > 0
                    ? VideoPlayerPlus(
                        VideoPlayerController.network(
                            swiperItems[index]['video_url']),
                      )
                    : CachedImage(
                        path: swiperItems[index]['img_url'],
                        width: MediaQuery.of(context).size.width,
                        height: 300.w,
                        scale: BoxFit.fill,
                      )),
          );
        },
        pagination: SwiperPagination(
            builder: DotSwiperPaginationBuilder(activeColor: Config.mainColor)),
      ),
    );
  }

  Widget _getDate(start, end) {
    var startTime = start.split(" ")[0];
    var endTime = end.split(" ")[0];
    return Container(
      // width: 300.w,
      margin: EdgeInsets.only(bottom: 10.0),
      child: Text(
        '有效期 $startTime -- $endTime',
        style: TextStyle(
          color: Color(0xff333333),
        ),
      ),
    );
  }

  /// 分栏
  Widget _tabs(TabController controller, List<Tab> tabList,
      {bool title = true}) {
    return Container(
      color: title ? EsColors.Primary : EsColors.White,
      child: Column(
        children: [
          TabBar(
            controller: controller,
            labelPadding: EdgeInsets.zero,
            labelColor: title ? EsColors.White : EsColors.Primary,
            labelStyle: TextStyle(
                fontSize: (title ? EsSizes.MD : EsSizes.MD) * 2.sp,
                fontWeight: EsFontWeights.Medium),
            isScrollable: false,
            unselectedLabelColor:
                title ? EsColors.White : EsColors.TitleSecondary,
            unselectedLabelStyle: TextStyle(
                fontSize: (title ? EsSizes.MD : EsSizes.SM) * 2.sp,
                fontWeight: EsFontWeights.Normal),
            indicatorSize: TabBarIndicatorSize.label,
            indicatorWeight: 8.w,
            indicatorPadding: EdgeInsets.only(bottom: 8.w),
            indicator: ExtendedUnderlineTabIndicator(
                borderSide: BorderSide(
                    color: title ? EsColors.White : EsColors.Primary,
                    width: 4.w)),
            tabs: List<Widget>.generate(
                tabList?.length ?? 0, (int index) => tabList[index]),
          ),
        ],
      ),
    );
  }

  /// 广告位
  Widget _adbox() {
    return AdBox(
      aspectRatio: 355 / 145,
      adKey: 'Adv',
      height: 145,
      borderRadius: 0,
      margin: EdgeInsets.zero,
      imageList: Adlist,
    );
  }

  ///筛选框
  Widget _screenBox() {
    return Padding(
      padding: EdgeInsets.all(24.w),
      child: Row(
          children: List<Widget>.generate(
        _screenList?.length ?? 0,
        (int index) => Expanded(
          child: GestureDetector(
            onTap: () {
              print('改变搜索条件:${_screenList[index]}');
              setState(() {
                _screenIndex = index;
                for (var i = 0; i < _screenList.length; i++) {
                  if (i == index) {
                    _screenList[i]['isSelected'] = true;
                    _screenList[i]['order'] = !_screenList[i]['order'];
                  } else {
                    _screenList[i]['isSelected'] = false;
                  }
                }
              });
            },
            child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
              Text(
                _screenList[index]['title'],
                style: TextStyle(
                    color: EsColors.Primary, fontSize: EsSizes.SM * 2.sp),
              ),
              _screenList[index]['isSelected']
                  ? Transform.rotate(
                      angle: _screenList[_screenIndex]['order'] ? 0 : -math.pi,
                      child: Icon(Icons.arrow_drop_up,
                          color: EsColors.Primary, size: 48.w))
                  : SizedBox(width: 48.w)
            ]),
          ),
        ),
      )),
    );
  }
}

class infoList extends StatefulWidget {
  ScrollController _scrollController;
  int ategory_id;

  infoList(this._scrollController, this.ategory_id, {Key key})
      : super(key: key);

  @override
  _infoListState createState() => _infoListState();
}

class _infoListState extends State<infoList> {
  int _progress = 0;
  List content_info_list;
  List advertising = [];

  dzfun(Map info) {
    var params2 = {
      'flag': info['is_like'] == 1 ? -1 : 1,
      'content_series': info['series'],
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };

    Api.contentlikes(params2).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          info['is_like'] == 1 ? info['likes_num']-- : info['likes_num']++;
          info['is_like'] == 1 ? info['is_like'] = -1 : info['is_like'] = 1;
        });
        // toast("修改成功");
      }
    });
  }

  dyfun(Map info) {
    var params2 = {
      'flag': info['is_collection'] == 1 ? -1 : 1,
      'content_series': info['series'],
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };

    Api.contentcollec(params2).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          info['is_collection'] == 1
              ? info['is_collection'] = -1
              : info['is_collection'] = 1;
        });
        // toast("修改成功");
      }
    });
  }

  getInfo() {
    var params2 = {
      'page_num': 1,
      'page_size': 100,
      'category_id': widget.ategory_id,
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };

    Api.contentquery(params2).listen((event) {
      if (event['code'] == 0) {
        if (event['content_info_list'] != null &&
            event['content_info_list'].length > 0) {
          setState(() {
            content_info_list = [];
            event['content_info_list'].forEach((element) {
              if (element['status_num_id'] == 3) {
                content_info_list.add(element);
              }
            });
          });
        }
        // toast("修改成功");
      }
    });
  }

  // 获取广告内容
  getAdvertising() {
    var params = {
      'adv_category': 5,
      'page_num': 1,
      'page_size': 10,
      'status_num_id': 3
    };
    Api.getAdvertising(params).listen((event) {
      if (event["code"] == 0 && event['list'] != null) {
        setState(() {
          advertising = event['list'];
        });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    getInfo();
    getAdvertising();
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener(
        onNotification: (ScrollNotification notification) {
          // 1.判断监听事件的类型

          if (notification is ScrollStartNotification) {
          } else if (notification is ScrollUpdateNotification) {
            // 当前滚动的位置和总长度
            final currentPixel = notification.metrics.pixels;
            final totalPixel = notification.metrics.maxScrollExtent;
            double progress = currentPixel / totalPixel;
            _progress = (progress * 100).toInt();
            if (notification.metrics.pixels > 200.w) {
              /// 有动画
              widget._scrollController.animateTo(420.w,
                  duration: Duration(milliseconds: 50), curve: Curves.easeIn);

              /// 无动画
              // _scrollController.jumpTo(210);
            }

            if (notification.metrics.pixels < 200.w) {
              widget._scrollController.animateTo(0,
                  duration: Duration(milliseconds: 100), curve: Curves.easeIn);
              // _scrollController.jumpTo(0);
            }
            // print(
            //     "正在滚动：${notification.metrics.pixels}-${notification.metrics.maxScrollExtent}");
          } else if (notification is ScrollEndNotification) {}
          return true;
        },
        child: content_info_list != null
            ? ListView.separated(
                padding: EdgeInsets.only(bottom: 210.w),
                itemBuilder: (context, index) =>
                    _item(content_info_list[index], index),
                separatorBuilder: (context, index) => YpLine(indent: 20.w),
                itemCount: content_info_list.length)
            : Container());
  }

  List<Widget> _newList(dynamic adList, int currentIndex) {
    var commonWidgets = List<Widget>();
    for (var item in adList) {
      if (item['adv_type'] == '1' && item['adv_line_num'] == currentIndex) {
        commonWidgets.add(Container(
          margin: EdgeInsets.only(bottom: 20.w),
          child: Stack(
            children: <Widget>[
              new Image(
                width: 750.r,
                height: 375.r,
                fit: BoxFit.fill,
                image: new NetworkImage(
                  item['adv_object_url'],
                ),
              ),
              item['tag_name'] != null
                  ? Positioned(
                      //方法二
                      right: 20.w,
                      bottom: 20.w,
                      child: new Container(
                        padding: EdgeInsets.only(
                          left: 6.0,
                          right: 6.0,
                          top: 2.0,
                          bottom: 2.0,
                        ),
                        decoration: BoxDecoration(
                          border: Border.all(
                            width: 1,
                            color: Color(0xff708090),
                          ),
                          borderRadius: BorderRadius.all(
                            Radius.circular(10),
                          ),
                        ),
                        child: Text(
                          item['tag_name'],
                          style: TextStyle(
                            color: Color(0xff708090),
                            fontSize: 10,
                          ),
                        ),
                      ),
                    )
                  : Container(),
            ],
          ),
        ));
      } else if (item['adv_type'] == '2' &&
          item['adv_line_num'] == currentIndex) {
        commonWidgets.add(
          Container(
            margin: EdgeInsets.only(bottom: 20.w),
            child: Stack(
              children: <Widget>[
                new VideoPlayerPlus(
                  VideoPlayerController.network(item['adv_object_url']),
                ),
                item['tag_name'] != null
                    ? Positioned(
                        //方法二
                        right: 20.w,
                        bottom: 20.w,
                        child: new Container(
                          padding: EdgeInsets.only(
                            left: 6.0,
                            right: 6.0,
                            top: 2.0,
                            bottom: 2.0,
                          ),
                          decoration: BoxDecoration(
                            // color: Color(0xff708090),
                            border: Border.all(
                              width: 1,
                              color: Color(0xff708090),
                            ),
                            borderRadius: BorderRadius.all(
                              Radius.circular(10),
                            ),
                          ),
                          child: Text(
                            item['tag_name'],
                            style: TextStyle(
                              color: Color(0xff708090),
                              fontSize: 10,
                            ),
                          ),
                        ),
                      )
                    : Container(),
              ],
            ),
          ),
        );
      } else if (item['adv_type'] == '3' &&
          item['adv_line_num'] == currentIndex) {
        Map<String, dynamic> user = jsonDecode(item['style_num_name']);
        user.forEach((key, value) {
          value[0]['shop_num_id'] = key;
          item['mdms_style'] = value[0];
        });
        commonWidgets.add(
          InkWell(
            onTap: () {
              String itemNumId =
                  item['mdms_style']['default_item_num_id'].toString();
              String styleNumId = item['mdms_style']['style_num_id'].toString();
              String ecStyleNumId =
                  item['mdms_style']['ec_style_num_id'].toString();
              Get.toNamed(RouteConfig.goodsDetail, arguments: {
                'itemNumId': itemNumId,
                'styleNumId': styleNumId,
                'shopId': item['mdms_style']['shop_num_id'],
                'ecStyleNumId': ecStyleNumId,
                'typeIndex': item['mdms_style']['is_pre_sale'] ?? 0,
              });
            },
            child: Container(
              margin: EdgeInsets.only(bottom: 20.w),
              padding: EdgeInsets.only(
                  left: 30.w, right: 30.w, top: 25.w, bottom: 15.w),
              decoration: BoxDecoration(
                  boxShadow: [BoxShadow(color: Colors.grey, blurRadius: 5.0.w)],
                  color: Colors.white,
                  borderRadius: new BorderRadius.circular((20.0.w))),
              child: Column(
                children: [
                  // Container(
                  //   alignment: Alignment.centerLeft,
                  //   margin: EdgeInsets.only(right: 10.w, bottom: 30.w),
                  //   child: Text(
                  //     item['mdms_style']['title'],
                  //     style: TextStyle(
                  //       color: Color(0xff333333),
                  //       fontWeight: FontWeight.bold,
                  //       fontSize: 32.w,
                  //     ),
                  //   ),
                  // ),
                  Container(
                    constraints: BoxConstraints(minHeight: 250.w),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          // width: 300.w,
                          child: Image.network(
                            item['mdms_style']['image_default_id'],
                            width: 250.w,
                            height: 220.w,
                            fit: BoxFit.cover,
                          ),
                        ),
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(left: 30.w),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    item['mdms_style']['style_num_name'],
                                    style: TextStyle(
                                      color: Color(0xff666666),
                                      fontWeight: FontWeight.bold,
                                      fontSize: 30.w,
                                    ),
                                  ),
                                ),
                                Stack(
                                  children: [
                                    item['tag_name'] != null
                                        ? Positioned(
                                            //方法二
                                            right: 0,
                                            bottom: 0,
                                            child: new Container(
                                              padding: EdgeInsets.only(
                                                left: 6.0,
                                                right: 6.0,
                                                top: 2.0,
                                                bottom: 2.0,
                                              ),
                                              decoration: BoxDecoration(
                                                // color: Color(0xff708090),
                                                border: Border.all(
                                                  width: 1,
                                                  color: Color(0xff708090),
                                                ),
                                                borderRadius: BorderRadius.all(
                                                  Radius.circular(30),
                                                ),
                                              ),
                                              child: Text(
                                                item['tag_name'],
                                                style: TextStyle(
                                                  color: Color(0xff708090),
                                                  fontSize: 10,
                                                ),
                                              ),
                                            ),
                                          )
                                        : Container(),
                                    Container(
                                      alignment: Alignment.centerLeft,
                                      margin: EdgeInsets.only(top: 80.w),
                                      child: Text(
                                        '¥ ${item['mdms_style']['price']}',
                                        style: TextStyle(
                                          color: Color(0xff666666),
                                          fontWeight: FontWeight.bold,
                                          fontSize: 30.w,
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      } else if (item['adv_type'] == '4' &&
          item['adv_line_num'] == currentIndex) {
        commonWidgets.add(
          InkWell(
            onTap: () {
              // 拼团
              if (item['results'][0]['ecactivity_classify'] == 1) {
                Map<String, dynamic> map = {
                  'icon_name': item['activity_num_name'],
                  'activity_num_id':item['activity_num_id'],
                  'pic_url': '',
                  'linktype': 9,
                  'linktarget': null,
                  'shop_id': item['results'][0]['ec_shop_num_id']
                };
                Get.toNamed(
                  RouteConfig.collage,
                  arguments: {'model': map},
                );
              } else if (item['results'][0]['ecactivity_classify'] == 2) {
                // 限时秒杀
                Map<String, dynamic> map = {'results': item['results']};
                Get.toNamed(
                  RouteConfig.seckillHome,
                  parameters: {},
                  arguments: {'model': map},
                );
              } else if (item['results'][0]['ecactivity_classify'] == 3) {
                // 预售
                Map<String, dynamic> map = {
                  'icon_name': item['activity_num_name'],
                  'pic_url': '',
                  'linktype': 12,
                  'linktarget': item['results'][0]['ecactivity_id'],
                  'shop_id': item['results'][0]['ec_shop_num_id'],
                };
                Get.toNamed(
                  RouteConfig.preSaleActive,
                  arguments: {'model': map},
                );
              } else {
                Map<String, dynamic> map = {
                  'icon_name': item['activity_num_name'],
                  'activity_num_id':item['activity_num_id'],
                  'pic_url': '',
                  'linktype': 9,
                  'linktarget': null
                };
                Get.toNamed(
                  RouteConfig.collage,
                  arguments: {'model': map},
                );
              }
            },
            child: Container(
              margin: EdgeInsets.only(bottom: 20.w),
              child: Stack(
                children: <Widget>[
                  item['results'].length != 0
                      ? new Image(
                          image: new NetworkImage(
                            item['activity_cover_url'],
                          ),
                        )
                      : Container(),
                  item['tag_name'] != null && item['results'].length != 0
                      ? Positioned(
                          //方法二
                          right: 20.w,
                          bottom: 20.w,
                          child: new Container(
                            padding: EdgeInsets.only(
                              left: 6.0,
                              right: 6.0,
                              top: 2.0,
                              bottom: 2.0,
                            ),
                            decoration: BoxDecoration(
                              border: Border.all(
                                width: 1,
                                color: Color(0xff708090),
                              ),
                              borderRadius: BorderRadius.all(
                                Radius.circular(30),
                              ),
                            ),
                            child: Text(
                              item['tag_name'],
                              style: TextStyle(
                                color: Color(0xff708090),
                                fontSize: 10,
                              ),
                            ),
                          ),
                        )
                      : Container(),
                ],
              ),
            ),
          ),
        );
      } else if (item['adv_type'] == '5' &&
          item['adv_line_num'] == currentIndex) {
        var data = jsonDecode(item['coupon_num_name']);
        commonWidgets.add(
          Container(
            child: ListView.builder(
              physics: NeverScrollableScrollPhysics() ,
              shrinkWrap: true,
              itemExtent: 160.0,
              itemCount: data.length,
              itemBuilder: (ctx, index) {
                return InkWell(
                  onTap: data[index]['cover_url'] == null
                      ? () {}
                      : () {
                          toast('领取中...');
                          var params = {
                            "use_platform": 2,
                            "coupon_num_id":
                                data[index]['series'].toString(), //券编码
                            "usr_num_id": SpUtil.getInt('empeNumId'),
                            "access_token": SpUtil.getString('token'),
                            "relation": "领券中心",
                            "qsource": 301,
                            "relation_indate": "永久有效",
                            "user_num_id": SpUtil.getInt('empeNumId'),
                          };
                          Api.getCoupon(params).listen(
                            (event) {
                              toastDismissOther(event['message']);
                            },
                          );
                        },
                  child: Container(
                    constraints: new BoxConstraints.expand(
                      height: 134.0,
                    ),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4.0),
                      image: DecorationImage(
                        image: NetworkImage("${data[index]['cover_url']}"),
                        fit: BoxFit.cover,
                      ),
                      color: Color(0xfff2c899),
                    ),
                    margin: EdgeInsets.only(bottom: 20.w, top: 20.w),
                    child: Row(
                      children: data[index]['cover_url'] != null
                          ? []
                          : [
                              Container(
                                width: 100.0,
                                margin: EdgeInsets.only(right: 20.w),
                                padding: EdgeInsets.only(left: 20.w),
                                child: Column(
                                  children: [
                                    Container(
                                      height: 30,
                                    ),
                                    data[index]['coupontype'] == '0'
                                        ? Row(
                                            children: [
                                              Text(
                                                '${data[index]['face_value'] / 10}',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                  fontSize: 36.0,
                                                ),
                                              ),
                                              Text(
                                                '折',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                ),
                                              ),
                                            ],
                                          )
                                        : Row(
                                            children: [
                                              Text(
                                                '¥',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                ),
                                              ),
                                              Text(
                                                '${data[index]['face_value']}',
                                                style: TextStyle(
                                                  color: Color(0xffa5673f),
                                                  fontSize: 36.0,
                                                ),
                                              ),
                                            ],
                                          ),
                                    Container(
                                      margin: EdgeInsets.only(top: 4.0),
                                      child: _couponType(
                                          data[index]['coupontype']),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Stack(
                                  children: [
                                    item['tag_name'] != null
                                        ? Positioned(
                                            //方法二
                                            right: 20.w,
                                            bottom: 20.w,
                                            child: new Container(
                                              padding: EdgeInsets.only(
                                                left: 6.0,
                                                right: 6.0,
                                                top: 2.0,
                                                bottom: 2.0,
                                              ),
                                              decoration: BoxDecoration(
                                                border: Border.all(
                                                  width: 1,
                                                  color: Color(0xff708090),
                                                ),
                                                borderRadius: BorderRadius.all(
                                                  Radius.circular(10),
                                                ),
                                              ),
                                              child: Text(
                                                item['tag_name'],
                                                style: TextStyle(
                                                  color: Color(0xff708090),
                                                  fontSize: 10,
                                                ),
                                              ),
                                            ),
                                          )
                                        : Container(),
                                    Container(
                                      // width: 400.w,
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            margin:
                                                EdgeInsets.only(bottom: 10.0),
                                            padding: EdgeInsets.only(top: 18.w),
                                            child: Text(
                                              data[index]['title'],
                                              style: TextStyle(
                                                color: Color(0xff000000),
                                                fontSize: 18.0,
                                              ),
                                            ),
                                          ),
                                          Container(
                                            child: item['start_time'] != null &&
                                                    item['end_time'] != null
                                                ? _getDate(item['start_time'],
                                                    item['end_time'])
                                                : Container(),
                                          ),
                                          InkWell(
                                            onTap: () {
                                              toast('领取中...');
                                              var params = {
                                                "use_platform": 2,
                                                "coupon_num_id": data[index]
                                                        ['series']
                                                    .toString(), //券编码
                                                "usr_num_id":
                                                    SpUtil.getInt('empeNumId'),
                                                "access_token":
                                                    SpUtil.getString('token'),
                                                "relation": "领券中心",
                                                "qsource": 301,
                                                "relation_indate": "永久有效",
                                                "user_num_id":
                                                    SpUtil.getInt('empeNumId'),
                                              };
                                              Api.getCoupon(params).listen(
                                                (event) {
                                                  toastDismissOther(
                                                      event['message']);
                                                },
                                              );
                                            },
                                            child: Container(
                                              padding: EdgeInsets.only(
                                                left: 10.0,
                                                right: 10.0,
                                                top: 4.0,
                                                bottom: 8.0,
                                              ),
                                              margin:
                                                  EdgeInsets.only(bottom: 20.w),
                                              decoration: BoxDecoration(
                                                color: Color(0xffa5673f),
                                                borderRadius:
                                                    BorderRadius.circular(20.0),
                                              ),
                                              child: Text(
                                                '立即领取',
                                                style: TextStyle(
                                                  color: Color(0xffffffff),
                                                  fontSize: 16,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                    ),
                  ),
                );
              },
            ),
          ),
        );
      }
    }
    return commonWidgets;
  }

//  优惠券类型
  Widget _couponType(String typeIndex) {
    var type = '折扣券';
    if (typeIndex == '0') {
      type = '折扣券';
    } else if (typeIndex == '1') {
      type = '现金券';
    } else if (typeIndex == '2') {
      type = '免邮券';
    } else if (typeIndex == '8') {
      type = '兑换券';
    }

    return Container(
      child: Text(
        type,
        style: TextStyle(
          color: Color(0xffa5673f),
          fontSize: 16,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  Widget _getDate(start, end) {
    var startTime = start.split(" ")[0];
    var endTime = end.split(" ")[0];
    return Container(
      // width: 300.w,
      margin: EdgeInsets.only(bottom: 10.0),
      child: Text(
        '有效期 $startTime -- $endTime',
        style: TextStyle(
          color: Color(0xff333333),
        ),
      ),
    );
  }

  Widget _item(Map info, int index1) {
    return GestureDetector(
      onTap: () {
        print('转跳');
        Get.toNamed(RouteConfig.eventDetail, arguments: {
          'is_like': info['is_like'], //是否点赞
          'likes_num': info['likes_num'], //
          'view_num': info['view_num'],
          'is_collection': info['is_collection'], //点赞数量
          'series': info['series']
        });
      },
      child: Padding(
        padding: EdgeInsets.all(24.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            InkWell(
              onTap: () {},
              child: advertising.length > 0 && index1 == 0
                  ? Column(
                      children: _newList(advertising, 1),
                    )
                  : Container(),
            ),
            Visibility(
              visible: info['img_url'] != null && info['img_url'].length > 0,
              child: CachedImage(
                  margin: EdgeInsets.only(bottom: 24.w),
                  width: double.infinity,
                  height: 404.w,
                  path: info['img_url']),
            ),
            Container(
              margin: EdgeInsets.only(top: 8.0, bottom: 10.0),
              alignment: Alignment.centerLeft,
              child: Text(
                '${info['title']}',
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: EsColors.Title,
                    fontSize: EsSizes.SM * 2.sp,
                    fontWeight: EsFontWeights.Normal),
              ),
            ),
            Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      print('点赞');
                      dzfun(info);
                    },
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Icon(
                              info['is_like'] == 1
                                  ? Icons.favorite
                                  : Icons.favorite_border,
                              color: info['is_like'] == 1
                                  ? EsColors.Primary
                                  : EsColors.ContentSecondary,
                              size: 32.w),
                          SizedBox(width: 4.w),
                          Text(
                            info['likes_num'].toString(),
                            style: TextStyle(
                                color: EsColors.Content,
                                fontSize: EsSizes.SM * 2.sp),
                          ),
                        ]),
                  ),
                ),
                Expanded(
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '浏览${info['view_num'].toString()}人',
                          style: TextStyle(
                              color: EsColors.Content,
                              fontSize: EsSizes.SM * 2.sp),
                        )
                      ]),
                ),
                Expanded(
                  child:
                      Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                    EsOutLineButton(
                        info['is_collection'] == 1 ? '取消订阅' : '+ 订阅',
                        borderColor: info['is_collection'] == 1
                            ? Colors.grey
                            : EsColors.Primary,
                        textColor: info['is_collection'] == 1
                            ? Colors.grey
                            : EsColors.Primary,
                        padding: EdgeInsets.symmetric(
                            horizontal: 24.w, vertical: 6.w), onTap: () {
                      print('订阅');
                      dyfun(info);
                    }),
                  ]),
                )
              ],
            ),
            SizedBox(height: 30.w),
            InkWell(
              onTap: () {},
              child: advertising.length > 0 && index1 >= 0
                  ? Column(
                      children: _newList(advertising, index1 + 2),
                    )
                  : Container(),
            ),
          ],
        ),
      ),
    );
  }
}
